package com.xm.xmwa1706090.service.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.internal.logging.InternalLoggerFactory;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Company 杭州新苗网络科技有限公司
 * @Author : loysen
 * @Description : {Neety启动类}
 */
@Component
public  class DeviceTCPServer {

	@Autowired
	private DeviceTCPServerInitializer deviceTCPServerInitializer;

	public void bind(int port,Integer nioEventLoopGroupNo) throws Exception {
		InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
		EventLoopGroup bossGroup = new NioEventLoopGroup(nioEventLoopGroupNo);
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			/*
			 * Netty5中ByteBuf对象的创建方式对内存的影响
			 * @see http://xiaochu.blog.51cto.com/1048262/1588426
			 */
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(deviceTCPServerInitializer)
					.option(ChannelOption.SO_BACKLOG, 1024)
					.option(ChannelOption.SO_RCVBUF, 1024 * 256)
					.option(ChannelOption.SO_SNDBUF, 1024 * 256)
					.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
					.childOption(ChannelOption.SO_KEEPALIVE, true);
			b.bind(port).sync().channel().closeFuture().sync();

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
